<script setup>
import { getArticlePageAPI, deleteArticleAPI } from '@/api'
import errorLogger from '@/utils/errorLogger'
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 跳转到文章编辑页，id 可选：有 id 为编辑，无 id 为创建
const gotoArticleEdit = (id) => {
  const params = {}
  if (id) params.id = id
  router.push({
    name: 'ArticleEdit', // 对应 router 中声明的 name
    params,
  })
}

// 分页获取文章列表
const articles = ref([])
const total = ref()
const pageParams = reactive({
  currentPage: 1,
  pageSize: 10,
})
const getArticles = async () => {
  try {
    const result = await getArticlePageAPI(pageParams)
    articles.value = result.data.list
    total.value = result.data.total
  } catch (error) {
    errorLogger(error)
  }
}
onMounted(() => {
  getArticles()
})

// 删除确认 popover 控制
const activePopoverId = ref(null)
const showPopover = (id) => (activePopoverId.value = id)
const hidePopover = () => (activePopoverId.value = null)

// 删除文章：调用 deleteArticleAPI 并刷新列表
const deleteArticle = async (id) => {
  try {
    await deleteArticleAPI(id)
    await getArticles()
    hidePopover()
    ElMessage.success('文章删除成功')
  } catch (err) {
    errorLogger(err)
  }
}
</script>

<template>
  <el-card>
    <template #header>
      <div>
        <el-text size="large">文章管理</el-text>
        <el-button
          type="primary"
          @click="() => gotoArticleEdit()"
          style="float: right">
          创建文章
        </el-button>
      </div>
    </template>

    <el-table :data="articles" style="width: 100%">
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="coverImage" label="封面图">
        <template #default="scope">
          <el-image
            :src="scope.row.coverImage"
            style="height: 100px; width: 100px"
            fit="cover">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="category.name" label="分类" />
      <el-table-column prop="createdAt" label="创建时间" />
      <el-table-column prop="updatedAt" label="更新时间" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            @click="gotoArticleEdit(scope.row._id)"
            size="small"
            type="primary"
            >编辑</el-button
          >
          <el-popover
            :visible="activePopoverId === scope.row._id"
            placement="top"
            :width="220">
            <p>确定要删除此文章吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="small" text @click="hidePopover">取消</el-button>
              <el-button
                size="small"
                type="primary"
                @click="deleteArticle(scope.row._id)"
                >确认</el-button
              >
            </div>
            <template #reference>
              <el-button
                size="small"
                type="danger"
                @click="showPopover(scope.row._id)"
                >删除</el-button
              >
            </template>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="pageParams.currentPage"
        v-model:page-size="pageParams.pageSize"
        layout="total, prev, pager, next"
        :total="total"
        @current-change="getArticles"
        background />
    </div>
  </el-card>
</template>

<style lang="scss" scoped>
.pagination {
  margin-top: 24px;
  @include flex-center;
}
</style>
